package com.zzb.weixin.model.menu;

import java.util.List;

import com.zzb.util.StringUtil;
import com.zzb.weixin.constant.Constant.WXEvent;
import com.zzb.weixin.constant.WXJsonName;
import com.zzb.weixin.json.JsonArray;
import com.zzb.weixin.json.JsonObject;

public class MenuItem {
	private List<MenuItem> subButton;//子菜单
	private String name;//菜单标题，不超过16个字节，子菜单不超过40个字节
	private WXEvent type;// view/click view是打开浏览器,click发送key
	private String key;//菜单KEY值，用于消息接口推送，不超过128字节
	private String url;//网页链接，用户点击菜单可打开链接，不超过256字节

	public MenuItem() {
	}

	public MenuItem(JsonObject jo) {
		this.setName(jo.getAsString(WXJsonName.NAME));
		String type = jo.getAsString(WXJsonName.TYPE);
		if (StringUtil.isEmpty(type)) {
			List<JsonObject> list = jo.getAsJsonArray(WXJsonName.SUB_BUTTON)
					.getAsJsonObjectList();
			for (JsonObject jsonObject : list) {
				subButton.add(new MenuItem(jsonObject));
			}
		} else {
			this.setType(WXEvent.valueOf(type.toUpperCase()));
			this.setUrl(jo.getAsString(WXJsonName.URL));
			this.setKey(jo.getAsString(WXJsonName.KEY));
		}
	}

	public List<MenuItem> getSubButton() {
		return subButton;
	}

	/**
	 * 添加二级子菜单
	 * 
	 * @param subButton
	 */
	public void setSubButton(List<MenuItem> subButton) {
		this.subButton = subButton;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public WXEvent getType() {
		return type;
	}

	public void setType(WXEvent type) {
		this.type = type;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public JsonObject toJson() {
		JsonObject jo = new JsonObject();
		jo.put(WXJsonName.NAME, name);
		if (subButton != null && subButton.size() > 0) {
			JsonArray ja = new JsonArray();
			for (MenuItem menu : subButton) {
				ja.add(menu.toJson());
			}
			jo.put(WXJsonName.SUB_BUTTON, ja);
		} else if (WXEvent.VIEW.equals(type)) {
			jo.put(WXJsonName.TYPE, type.toString().toLowerCase());
			jo.put(WXJsonName.URL, url);
		} else {
			jo.put(WXJsonName.TYPE, type.toString().toLowerCase());
			jo.put(WXJsonName.KEY, key);
		}
		return jo;
	}
}
